package cn.wh.beans.factory.support;

import cn.wh.beans.BeansException;
import cn.wh.beans.factory.config.BeanDefinition;
import cn.wh.beans.factory.config.BeanPostProcessor;
import cn.wh.beans.factory.config.ConfigurableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: wh
 * @create: 2022-08-31 15:26
 * @description
 **/
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {
    private final List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }

    protected <T> T doGetBean(final String name, Object[] args) {
        //在单例注册表中获取容器
        Object bean = getSingleton(name);
        if (bean == null) {
            //获取注册表中bean
            BeanDefinition beanDefinition = getBeanDefinition(name);
            bean = createBean(name, beanDefinition, args);
        }
        return (T)bean;
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessorList.remove(beanPostProcessor);
        this.beanPostProcessorList.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessorList() {
        return beanPostProcessorList;
    }
}
